package com.zhihuishu.treenity.service.tools.impl;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;

import com.able.base.ftp.oss.OSSPublicUploadInterface;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.treenity.consts.ToolsConsts;
import com.zhihuishu.treenity.dto.ImageCutDto;
import com.zhihuishu.treenity.dto.ImageDto;
import com.zhihuishu.treenity.helper.UUIDHelper;
import com.zhihuishu.treenity.service.tools.ImageCutService;
import com.zhihuishu.treenity.util.DataSource;
import com.zhihuishu.treenity.util.ImageUtil;
import com.zhihuishu.treenity.util.StringUtils;

import net.sf.json.JSONObject;

@Service("imageCutService")
public class ImageCutServiceImpl implements ImageCutService{
	
	//全图参数验证
	public Boolean checkCutISEmpty(ImageDto imageDto){
		
		if(!StringUtils.isNotEntity(imageDto.getUrl())){
			return false;//网络图片地址不为空
		}else if(!StringUtils.isNotEntityOfInteger(imageDto.getLeftX(),1)){
			return false;//裁剪图片X轴 >=0
		}else if(!StringUtils.isNotEntityOfInteger(imageDto.getLeftY(),1)){
			return false;//裁剪图片Y轴 >=0
		}else if(!StringUtils.isNotEntityOfInteger(imageDto.getWidth(),-1)){
			return false;//裁剪图片宽度 >0
		}else if(!StringUtils.isNotEntityOfInteger(imageDto.getHeight(),-1)){
			return false;//裁剪图片高度 >0
		}
		return true;
	}
	
	//裁剪
	 public RemoteResult<DataSource> ImageCut(ImageDto imageDto,Double dealtWidth,Double dealtHeight){
		 RemoteResult<DataSource> remoteResult =new RemoteResult<DataSource>();
		 String message="";
		 long startTime = new Date().getTime();
		 if(checkCutISEmpty(imageDto)){
			 
			 try {
		    			String uploadCutIamageUrl = "";
			    		String url = imageDto.getUrl();
			    		BufferedImage bi = null;
			    		
			    		//type  1.原图裁剪   2.指定宽高压缩比例裁剪
			    		if(imageDto.getCutType() ==1){
			    			bi = ImageUtil.cutImage(imageDto.getLeftX(),imageDto.getLeftY(),imageDto.getWidth(),imageDto.getHeight(),imageDto.getUrl());
			    		}else if(imageDto.getCutType() ==2){
			    			bi = thumbnailCut(imageDto,dealtWidth,dealtHeight);
			    		}
												
						//考虑到不规范的图片格式（.jPg、.Jpg、.jpG）
						//将图片格式统一转换成小写
						//图片类型 jpg、png、gif
						String suffixName = url.substring(url.lastIndexOf(".") + 1, url.length()).toLowerCase();
						//图片后缀 .jpg 、.png、.gif
						String pointAddSuffixName = url.substring(url.lastIndexOf("."), url.length()).toLowerCase();
						//生成UUID字符串(32位)
						String uuid = UUIDHelper.uuid();
						File iiow = File.createTempFile(uuid, pointAddSuffixName);
						ImageIO.write(bi, suffixName, iiow);
						
						//调用base组进行上传 ，返回result结果接
						String result=OSSPublicUploadInterface.imgUpload(iiow, ToolsConsts.appName, ToolsConsts.modelName);
						
						if(StringUtils.isNotEntity(result)){
							JSONObject resultJson = JSONObject.fromObject(result);
					    	JSONObject resultDataJson = JSONObject.fromObject(resultJson.getString("data"));
					    	//System.out.println(resultJson.toString());
					    	message=resultJson.getString("message");
					    	
					    	//如果data有数据上传成功，否则上传失败
					    	if(resultDataJson.size() >0){
					    		uploadCutIamageUrl = resultDataJson.getString("path");
					    		iiow.delete();
								
								long endTime=new Date().getTime() - startTime;
								remoteResult.setSuccess(true);
								remoteResult.setResult(new DataSource(uploadCutIamageUrl,endTime,message));

								return remoteResult;
					    	}
						}
							
				} catch (Exception e) {
					 remoteResult.setExceptionStack(e);
				}
		 }else{
			 remoteResult.setExceptionStack(new Exception("裁剪图片的参数有误！"));
		 }
		 	remoteResult.setSuccess(false);
		 	remoteResult.setResult(new DataSource(null,(new Date().getTime() - startTime),message));
	    	
	    	return remoteResult;
	    }
	 
	
		/**
		 * 功能：获取压缩的尺寸
		 * 
		 * @param realWidth  	//原图宽度
		 * @param realHeight  	//原图高度
		 * @param finalWidth  	//定义默认压缩的宽度
		 * @param finalHeight   //定义默认压缩的高度
		 * @return
		 */
		public static ImageCutDto getfinalCutSize(Double realWidth, Double realHeight,final Double finalWidth,final Double finalHeight) {
			if (realWidth != null && realHeight != null && finalWidth!=null && finalHeight!=null) {

				Double oldRealWidth = realWidth;
				Double oldRealHeight = realHeight;
				Boolean flag = false;
				// 如果宽高超出裁剪限定的范围 ,进行缩放
				// 1.如果超出宽度，按照宽度的比例缩放

				if (realWidth > finalWidth) {
					realWidth = finalWidth;
					realHeight = (finalWidth * (oldRealHeight / oldRealWidth));
					//System.out.println("oldW:"+oldRealWidth+"——oldH:"+oldRealHeight+"====needW:"+finalWidth+"====needH:"+finalHeight);
					//System.out.println("first: width:" + realWidth + "=======height:" + realHeight);
					flag = true;
				}

				if (realHeight > finalHeight) {
					realHeight = finalHeight;
					realWidth = finalHeight * (oldRealWidth / oldRealHeight);
					//System.out.println("oldW:"+oldRealWidth+"——oldH:"+oldRealHeight+"====needW:"+finalWidth+"====needH:"+finalHeight);
					//System.out.println("Two: width:" + realWidth + "=======heigth:" + realHeight);
					flag = true;
				}
				realWidth = Double.valueOf((String.format("%.1f", realWidth)));
				realHeight = Double.valueOf(String.format("%.1f", realHeight));

				return new ImageCutDto(realWidth, realHeight, flag);
			}

			return null;
		}

	/**
	 * 功能：压缩比例图片裁剪
	 * 
	 * @param ImageDto  	
	 * @param dealtWidth 	//定义默认压缩的宽度
	 * @param dealtHeight	//定义默认压缩的高度
	 * @return 
	 */
	public static BufferedImage thumbnailCut(ImageDto imageDto,Double dealtWidth,Double dealtHeight) {

		Image img = null; 					// Image对象
		ImageFilter cropFilter=null;		// 裁剪对象
		BufferedImage bi = null;			// 读取源图像
		ImageProducer resource=null;        // 生成图像像素的对象
		try {

			bi = ImageIO.read(new URL(imageDto.getUrl()));
			Integer srcWidth = bi.getWidth(); 	// 源图宽度
			Integer srcHeight = bi.getHeight(); // 源图高度
			
			//获取可压缩的图片比例
			ImageCutDto cut = getfinalCutSize(srcWidth.doubleValue(), srcHeight.doubleValue(),dealtWidth,dealtHeight);
			System.out.println(cut);
			if (cut != null && cut.getFlag()) {
				img = bi.getScaledInstance(cut.getCutWidth().intValue(), cut.getCutHeight().intValue(), Image.SCALE_DEFAULT);// 获取缩放后的图片大小
				resource=img.getSource();
			}else{
				resource=bi.getSource();
			}
			

			cropFilter = new CropImageFilter(imageDto.getLeftX(), imageDto.getLeftY(), imageDto.getWidth(), imageDto.getHeight());// 裁剪对象

			img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(resource, cropFilter));
			BufferedImage tag = new BufferedImage(imageDto.getWidth(), imageDto.getHeight(), BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			// 在画图的时候可以设置背景色
			g.drawImage(img, 0, 0, Color.white, null);
			g.dispose();
			
//			if(imageDto.getSubPath()!=null && imageDto.getSubPath()!=""){
//				ImageIO.write(tag, getExtention(imageDto.getUrl()), new File(imageDto.getSubPath()));
//			}
			return tag;
		} catch (IOException e1) {
			System.out.println(e1.getMessage());
		}
		return null;
	}
	
	/**
	 * 功能：提取文件名的后缀
	 * 
	 * @param fileName
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos + 1);
	}
	

}
